package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import io.swagger.models.auth.In;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
//    @Value("${sky.shop.address}")
//    private String shopAddress;
//    @Value("${sky.baidu.ak}")
//    private String ak;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 新增订单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.验证用户的地址信息
        //根据订单地址id查询当前地址信息
       AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
       //判断地址信息是否为空
        if(addressBook == null ){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.验证用户购物车信息
        ShoppingCart shoppingCart = new ShoppingCart();
        //设置用户id
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list.isEmpty() || list == null){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.向订单表插入一条数据
        //新建一个订单对象
        Orders orders = new Orders();
        //拷贝对象属性
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //设置相关属性
        //订单创建时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置订单号 时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置用户手机号
        orders.setPhone(addressBook.getPhone());
        //设置用户收货人姓名
        orders.setConsignee(addressBook.getConsignee());
        //设置用户id
        orders.setUserId(userId);
        //设置用户地址
        orders.setAddress(addressBook.getDetail());
        //插入数据到订单表
        orderMapper.insert(orders);
        //4.向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();//创建对象
            BeanUtils.copyProperties(cart,orderDetail);//拷贝对象属性
            orderDetail.setOrderId(orders.getId());//设置订单id
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBeach(orderDetails);//批量插入数据
        //5.清除购物车
        shoppingCartMapper.deleteAll(userId);
        //6.封装返回对象
        return  OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();


    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //通过websocket向客户端游览器推送消息 type,orderId content
        Map map = new HashMap();
        map.put("type",1);//1 新订单 2  催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        //订单详情orderDetailList
        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) { //有订单才有必要接着查询订单详情信息
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id
                // 根据订单id,查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                //拷贝对象属性
                BeanUtils.copyProperties(orders, orderVO);
                // 将订单明细放入订单数据中返回
                orderVO.setOrderDetailList(orderDetails);
                List<String> orderDish = new ArrayList<>();
                for (OrderDetail detail : orderDetails) {
                   String name =  detail.getName();
                   Integer number = detail.getNumber();
                   orderDish.add(name+"*"+number);
                }
                String orderDishesString = String.join(", ", orderDish);
                orderVO.setOrderDishes(orderDishesString);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 根据id查询订单详细详细
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        if(orders != null){
            Long orderId = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
            orderVO.setOrderDetailList(orderDetails);
        }
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.getById(id);
        Integer status = orders.getStatus();
        if(status == Orders.CONFIRMED ||status == Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR+"订单派送或已接单，请联系商家取消");
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 在来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        //根据订单id查询订单明细
        Long orderId = orders.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        //订单明细列表加入到购物车
        for (OrderDetail orderDetail : orderDetailList) {
            //创建一个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            //拷贝属性
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            //设置用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            //设置当前时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            //插入到购物车中
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 查询各个状态的订单数量
     * @return
     */
    @Override
    public OrderOverViewVO getOverView() {
        //全部订单
        Map map = new HashMap();
        Integer allOrders = orderMapper.countByMap(map);
        //待接单
        Integer waitingOrders = orderMapper.getByStatus(Orders.REFUND);
        //待派送
        Integer deliveredOrders = orderMapper.getByStatus(Orders.CONFIRMED);
        //派送中
        Integer deliveryInProgress = orderMapper.getByStatus(Orders.DELIVERY_IN_PROGRESS);
        //已完成
        Integer completedOrders = orderMapper.getByStatus(Orders.COMPLETED);
        //已取消
        Integer cancelledOrders = orderMapper.getByStatus(Orders.CANCELLED);
        return new OrderOverViewVO(waitingOrders,deliveredOrders,completedOrders,cancelledOrders,deliveryInProgress,allOrders);

    }

    /**
     * 订单状态更改
     * @param ordersConfirmDTO
     */
    @Override
    public void updateStatus(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.update(Orders.builder().id(ordersConfirmDTO.getId()).status(ordersConfirmDTO.getStatus()).build());
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        //设置id
        orders.setId(ordersCancelDTO.getId());
        //设置订单状态
        orders.setStatus(Orders.CANCELLED);
        //设置订单取消原因
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        //设置取消时间
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        //设置id
        orders.setId(ordersRejectionDTO.getId());
        //设置订单状态
        orders.setStatus(Orders.CANCELLED);
        //设置拒单原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        //设置取消时间
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        //判断订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if(orders.getStatus() == Orders.REFUND){
            //通过websocket向客户端游览器推送消息 type,orderId content
            Map map = new HashMap();
            map.put("type",2);//1 新订单 2  催单
            map.put("orderId",orders.getId());
            map.put("content","订单号："+orders.getNumber());
            String json = JSON.toJSONString(map);
            webSocketServer.sendToAllClient(json);
        }
    }
}
